import Taro, { getStorageSync, useLoad, useRouter } from '@tarojs/taro'
import { MyResponse, getSingleOrderInfoByID } from '@/api/myOrder'
import { useState } from 'react'
import { AtMessage } from 'taro-ui'
import { OrderDetail } from '@/pages/pay/type'
import OrderInfo from './components/OrderInfo'
import styles from './index.module.scss'

export default function OrderDetailed() {
  const router = useRouter()
  const [orderInfo, setOrderInfo] = useState<OrderDetail>()

  const handlePay = () => {
    Taro.navigateTo({
      url: `/pages/pay/index?id=${orderInfo?.id}`,
    })
  }

  const handleCancelOrder = async () => {
    try {
      const res = await Taro.request({
        url: `${process.env.TARO_APP_API}/order/api/v1/order/cancel?orderId=${orderInfo?.id}&goodsId=${orderInfo?.productId}`,
        method: 'PUT',
        header: {
          'content-type': 'application/json', // 默认值
          token: getStorageSync('token'),
        },
      })
      if (res && res.code === 0) {
        Taro.showToast({
          title: '订单取消成功',
          icon: 'success',
          duration: 1000,
        })
        setTimeout(() => Taro.navigateBack(), 1000)
      } else {
        const errorMsg = res && res.msg ? res.msg : 'Unknown error'
        Taro.showToast({
          title: errorMsg,
          icon: 'error',
        })
      }
    } catch (error) {
      console.log('出现错误')
    }
  }

  const handleDeleteOrder = async () => {
    try {
      const res: MyResponse = await Taro.request({
        url: `${process.env.TARO_APP_API}/order/api/v1/order/deleteById?orderId=${orderInfo?.id}&goodsId=${orderInfo?.productId}`, //仅为示例，并非真实的接口地址
        method: 'DELETE',
        header: {
          'content-type': 'application/json', // 默认值
          token: getStorageSync('token'),
        },
      })
      if (res && res.code === 0) {
        Taro.showToast({
          title: '订单删除成功',
          icon: 'success',
          duration: 1000,
        })
        setTimeout(() => Taro.navigateBack(), 1000)
      } else {
        const errorMsg = res && res.msg ? res.msg : 'Unknown error'
        Taro.showToast({
          title: errorMsg,
          icon: 'error',
        })
      }
    } catch (error) {
      console.log('出现错误')
    }
  }

  const handleToGoodPage = () => {
    Taro.navigateTo({
      url: `/pages/productDetail/index?id=${orderInfo?.productId}`,
    })
  }

  useLoad(() => {
    const { id } = router.params

    const fetchGetSingleOrderInfoByID = async () => {
      try {
        const { data } = await getSingleOrderInfoByID(id as string)
        console.log('获取到的订单详情', data)
        setOrderInfo(data.orderDetail)
      } catch (err) {
        console.log('获取订单详情失败', err)
      }
    }
    fetchGetSingleOrderInfoByID()
  })

  return (
    <>
      <div className={styles.orderDetail}>
        <div>
          <div className={styles.pageHeader}>
            <div className={styles.orderStatus}>
              {orderInfo?.status === 0
                ? '待支付'
                : orderInfo?.status === 1
                  ? '已取消'
                  : '已支付'}
            </div>
          </div>
          <div className={styles.orderItem}>
            <div className={styles.orderContent}>
              <div className={styles.orderContentLeft}>
                <img
                  className={styles.img}
                  src={orderInfo?.productCover}
                  alt=''
                />
              </div>
              <div className={styles.orderContentRight}>
                <div className={styles.goodsDesc}>{orderInfo?.productName}</div>
                <div className={styles.goodsNum}>x{orderInfo?.count}</div>
                <div className={styles.goodsPrice}>
                  实付：¥{orderInfo?.price}
                </div>
              </div>
            </div>
            <div className={styles.orderFooter}>
              <div
                className={styles.productDetailBtn}
                onClick={handleToGoodPage}
              >
                <span className={styles.pdSpan}>查看商品详情</span>
              </div>
            </div>
          </div>
          <OrderInfo
            id={orderInfo?.id}
            payMethod={orderInfo?.payMethod}
            createTime={orderInfo?.createTime}
          ></OrderInfo>
        </div>
        <div className={styles.action}>
          {(orderInfo?.status === 1 || orderInfo?.status === 2) && (
            <div className={styles.deleteBtn} onClick={handleDeleteOrder}>
              删除订单
            </div>
          )}
          {orderInfo?.status == 0 && (
            <>
              <div className={styles.payBtn} onClick={handlePay}>
                <span>去支付</span>
              </div>
              <div className={styles.cancelBtn} onClick={handleCancelOrder}>
                <span>取消订单</span>
              </div>
            </>
          )}
        </div>
      </div>
      <AtMessage />
    </>
  )
}
